package com.lijiajian.aspect;

import com.lijiajian.annoation.RequiredPermission;
import com.lijiajian.exceptions.AuthException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.List;

import static com.alibaba.druid.sql.ast.SQLPartitionValue.Operator.List;

@Component
@Aspect
public class PermissionProxy {
    @Resource
    private HttpSession session;
    @Around(value="@annotation(com.lijiajian.annoation.RequiredPermission)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object result=null;
        List<String> permissions =(java.util.List<String>) session.getAttribute("permissions");
        //判断用户是否拥有权限
        if(null==permissions||permissions.size()<1){
            throw new AuthException();
        }
        //得到对应目标
        MethodSignature signature = (MethodSignature)pjp.getSignature();
        //得到方法上的注解
        RequiredPermission annotation = signature.getMethod().getAnnotation(RequiredPermission.class);
        //判断注解上对应的状态码
        if(!(permissions.contains(annotation.code()))){
            throw new AuthException();
        }

        result = pjp.proceed();

        return result;
    }

}
